package com.util;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class HttpClientUtil {

	public static int timeout = 30000;

	public static String doPostWithJsonResult(String uri, Map<String, Object> paramMap) {
		String json=GsonUtil.toJson(paramMap);
		json=AESUtil.Encrypt(json);
		return doPost(uri,json);
	}
	public static String doPost(String uri, String jsonStr) {
		System.out.println("========= Call ["+uri+"] Start ==========");
		URL u = null;
		HttpURLConnection con = null;
		try {
			u = new URL(GetConfig.getString("url")+uri);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setConnectTimeout(timeout);
			con.setReadTimeout(timeout);
			//con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			//con.setRequestProperty("content-type", "*/*");
			if(jsonStr != null && !"".equals(jsonStr)){
				OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
				System.out.println("即将发送参数:"+jsonStr);
				osw.write(URLEncoder.encode(jsonStr));
				osw.flush();
				osw.close();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		// 读取返回内容
		StringBuffer buffer = new StringBuffer();
        BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp = "";
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}
		} catch (Exception e) {
			System.out.println(e);
			return null;
		}finally {
		    if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        String result = buffer.toString();
		System.out.println("Payload: "+result);
		System.out.println("========= Call ["+uri+"] End =========");
		return result.substring(1,result.length()-1).replace("\\","");
	}

	/**
	 * 发送get请求
	 * @param url
	 * @param param
	 * @param cookie
	 * @return
	 */
	public static String sendGet(String url, String param,String cookie) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString ="";
			if(param==null){
				urlNameString = url ;
			}else{
				urlNameString = url + "?" + param;
			}
			System.out.println(urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            connection.setRequestProperty("user-agent","Koala Admin");
			if(cookie!=null){
				connection.setRequestProperty("Cookie", cookie);
			}
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String doPost(String uri, String jsonStr,int time) {
		timeout=time;
		return doPost(uri,jsonStr);
	}

	public static Map<String,Object> getComMap(String tokenValue,String registerName,String memKey){
		String token = GetConfig.getString("accessToken");
		String accessToken = AESUtil.Encrypt(token);
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("accessToken",accessToken);
		param.put("tokenValue",tokenValue);
		param.put("registerName",registerName);
		param.put("memKey",memKey);
		return param;
	}
	public static String getComJson(String registerName,String memKey){
		return GsonUtil.toJson(getComMap("100",registerName,memKey));
	}

	public static void main(String[] args) {
		String url = "Logistics/MEM/GetAccessToken";
		String token = "888H615#Cl3OysbBz1E6$71fewe#h100";
		String accessToken = AESUtil.Encrypt(token);
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("accessToken",accessToken);
		param.put("tokenValue","100");
		param.put("registerName","");
		param.put("memKey","");
	    HttpClientUtil clientUtil = new HttpClientUtil();
	    clientUtil.doPostWithJsonResult(url,param);
	}
}
